<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPermissionAnchorModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserExtContractModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\OpenShop\StartBusiness\OpenShopStartBusinessModel;
use App\Service\Guanyuan\CurlService;
use App\Service\OpenShop\Feishu\MessageSendService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\Feishu\ShopManualService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\User\RmsUserService;
use App\Support\OrganizationManageFsRobotSendSupport;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;

class ModifyOrderSignUserInfo extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'open_shop:modify-order-user-info {shopCode} {--name=} {--mobile=} {--inviterName=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '手动修改开店订单数据 .';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private array $modifyStartField = [];

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $shopCode    = (int)$this->argument('shopCode');
        $name        = $this->option('name');
        $mobile      = $this->option('mobile');
        $inviterName = $this->option('inviterName');


        $signOrderList = OpenShopSignOrderModel::query()->with('baseInfoRel')->with('identityCardRel')
                                               ->where('shopCode', $shopCode)
                                               ->where('status', '!=', 0)
                                               ->get();

        if (empty($signOrderList->count())) {
            $this->info('查无此订单 结束操作');
            return;
        }
        $str = '';
        foreach ($signOrderList as $signOrder) {

            if (!empty($name)) {
                $signOrder->identityCardRel->name = $name;
                $signOrder->identityCardRel->save();
                $str .= '加盟商姓名 ';
            }

            if (!empty($mobile)) {
                $signOrder->baseInfoRel->mobile = $mobile;
                $signOrder->baseInfoRel->save();
                $str .= '加盟商手机号 ';
            }

            if (!empty($inviterName)) {

                // 获取所有人列表
                $list = OrderService::getFeishuUserDepartmentList();

                $listAll = [];
                foreach ($list as $one) {
                    $itemOne = [];
                    foreach ($one['children'] as $item) {
                        $itemOne[] = [
                            'inviterId'      => $item['value'],
                            'inviterName'    => $item['label'],
                            'departmentName' => $one['label'],
                        ];
                    }

                    $listAll = array_merge($listAll, $itemOne);
                }
                $listAll = collect($listAll);
                $inviterName = str_replace(['（','）'], ['(', ')'], $inviterName);
                $pattern = '/^(.*?)\((.*?)\)$/';

                $inviterName = preg_replace_callback($pattern, function($matches) {
                    // $matches[1] 是括号外的内容，$matches[2] 是括号内的内容
                    return $matches[2] . '(' . $matches[1] . ')';
                }, $inviterName);

                $inviterInfo = $listAll->where('inviterName', $inviterName)->first();
                if (!empty($inviterInfo)) {

                    $departmentName = $inviterInfo['departmentName'];
                    $departmentName = str_replace('办公室', '分公司', $departmentName);

                    $signOrder->lastFinishContractRel->inviterId      = $inviterInfo['inviterId'];
                    $signOrder->lastFinishContractRel->inviterName    = $inviterInfo['inviterName'];
                    $signOrder->lastFinishContractRel->departmentName = $inviterInfo['departmentName'];
                    $signOrder->lastFinishContractRel->save();
                }
                $str .= '加盟商推荐人';
            } else {
                $signOrder->lastFinishContractRel->inviterId      = 0;
                $signOrder->lastFinishContractRel->inviterName    = "";
                $signOrder->lastFinishContractRel->departmentName = "";
                $signOrder->lastFinishContractRel->save();
            }
        }

        $this->info($str . ' 更新成功');

    }
}
